using Autofac;
using Autofac.Extensions.DependencyInjection;
using Hangfire;
using Hangfire.MySql;
using Hangfire.SqlServer;
using IGeekFan.AspNetCore.Knife4jUI;
using Infrastructure;
using Microsoft.Extensions.Options;

using NLog.Web;
using ServiceManagement.Consul;
using SqlSugar;
using Yitter.IdGenerator;
using YSL.Api.Host.Controllers;
using YSL.Application;
using YSL.Application.Dynamics;
using YSL.Application.Services.Qiniu;
using YSL.Application.Services.定时任务;
using YSL.Application.Ysl_Dto.Input;
using YSL_Domain.Model;



var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//全局异常处理
builder.Services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    var file = AppContext.BaseDirectory + "YSL.Api.Host.xml";
    o.IncludeXmlComments(file, true);
});




#region Redis配置

// 注册Redis连接
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
    options.InstanceName = "DataDict:";//数据字典专用前缀
});
//注册数据字典服务
builder.Services.AddScoped<RedisDataDictionaryService>();
#endregion

#region 类的依赖注入
//添加autofac
builder.Services.AddAutofac();
//批量依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory(x => x.RegisterModule(new Ysl_GolabAutofacProfile())));
//automapper
builder.Services.AddAutoMapper(typeof(Ysl_AutomapperFile));
//雪花id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
//仓储
builder.Services.AddScoped(typeof(MesRepository<>));

//网关
builder.Configuration.Register();
//日志
builder.Host.UseNLog();

#endregion

#region   SqlSugar框架配置







//创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = builder.Configuration.GetConnectionString("Connection_DB"),
    DbType = DbType.MySql,
    //ConnectionString = builder.Configuration.GetConnectionString("Connection_DB"),
    //DbType = DbType.Oracle,
    IsAutoCloseConnection = true
},
db =>
{

    db.Aop.OnLogExecuting = (sql, pars) =>
    {

        //获取原生SQL推荐 5.1.4.63  性能OK
        Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));

        //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
        //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))


    };  //创建实体类
    //db.DbFirst.IsCreateAttribute().CreateClassFile("D:\\我的物联网\\大一实训\\大一项目MES 系统\\服务端\\SmartFactory\\SmartFactory\\B.MES.YSL_Domain\\Model");

    //db.GetConnection(i).Aop
    ////建库
    //db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库

    ////建表（看文档迁移）
    //db.CodeFirst.InitTables<CODE_RULE>(); //所有库都支持  
    //db.CodeFirst.InitTables<CODE_SERIAL>(); //所有库都支持
    //db.CodeFirst.InitTables<YSL_PACKAGE>(); //所有库都支持
    //db.CodeFirst.InitTables<YSL_PRODUCT_LOCK>(); //所有库都支持
    //db.CodeFirst.InitTables<YSL_WORKORDER>(); //所有库都支持
});

////建库
//Db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库

////建表（看文档迁移）
//Db.CodeFirst.InitTables<CODE_RULE>(); //所有库都支持  
//Db.CodeFirst.InitTables<CODE_SERIAL>();
//Db.CodeFirst.InitTables<YSL_PACKAGE>(); 
//Db.CodeFirst.InitTables<YSL_PRODUCT_LOCK>(); 
//Db.CodeFirst.InitTables<YSL_WORKORDER>(); 


//注册上下文：AOP里面可以获取IOC对象，如果有现成框架比如Furion可以不写这一行
builder.Services.AddHttpContextAccessor();
//注册SqlSugar用AddScoped
builder.Services.AddScoped<ISqlSugarClient>(s =>
{
    //Scoped用SqlSugarClient 
    SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
    {
        //DbType = SqlSugar.DbType.Oracle,
        //ConnectionString = builder.Configuration.GetConnectionString("Connection_DB"),
        ConnectionString = builder.Configuration.GetConnectionString("Connection_DB"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
    },
   db =>
   {
       //每次上下文都会执行

       //获取IOC对象不要求在一个上下文
       //var log=s.GetService<Log>()

       //获取IOC对象要求在一个上下文
       //var appServive = s.GetService<IHttpContextAccessor>();
       //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

       db.Aop.OnLogExecuting = (sql, pars) =>
       {

       };

       //注意多租户 有几个设置几个
   });
    return sqlSugar;
});

#endregion

#region 七牛云
//七牛云
builder.Services.AddSingleton<QiniuService>(new QiniuService(
    "s04HIPKKemvqimiURQ-e1-tPO4hKhGcMeO6eXAru",
    "mVVPITWbOK1Idvne6T-7k3sBqbhukLlbTX5mUP5n",
    "traceability-0527",
    "swwu3r93n.hd-bkt.clouddn.com"
));
#endregion





#region Hangfire配置


//添加Hangfire
builder.Services.AddHangfire(configuration => configuration
       .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
       .UseSimpleAssemblyNameTypeSerializer()
       .UseRecommendedSerializerSettings()
       .UseStorage(new MySqlStorage(builder.Configuration.GetConnectionString("HangfireConnection"), new MySqlStorageOptions
       {
           //CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
           //SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
           //QueuePollInterval = TimeSpan.Zero,
           //UseRecommendedIsolationLevel = true,
           //DisableGlobalLocks = true
       })));
// .UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection")));

// 添加 Hangfire 服务
builder.Services.AddHangfireServer();



builder.Services.AddScoped<IHangfireService, HangfireService>();
#endregion





var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
     app.UseKnife4UI();
   // app.UseSwaggerUI();
}
//访问 Hangfire 仪表板
app.MapHangfireDashboard();
//BackgroundJob.Enqueue<WorkOrderController>(x =>x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }));
//RecurringJob.AddOrUpdate<WorkOrderController>(
//    "SetRedisDictionaryJob",
//     x => x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }),
//    "0,10,20,30,40,50 * * * * ? ");

//app.MapHangfireDashboard();
BackgroundJob.Enqueue<WorkOrderController>(x => x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }));
 
RecurringJob.AddOrUpdate<WorkOrderController>(
    "SetRedisDictionaryJob",
     x => x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }),
    "0,10,20,30,40,50 * * * * ?");
//BackgroundJob.Enqueue<IHangfireService>(x => x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }));
//RecurringJob.AddOrUpdate<IHangfireService>(
//    "SetRedisDictionaryJob",
//    x => x.RefreshAllDataAsync(new HangfirePageInput { PageIndex = 1, PageSize = 10 }),
//    "0,10,20,30,40,50 * * * * ?");

 
app.UseAuthorization();
//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
//静态文件
app.UseStaticFiles();
app.MapControllers();
// 定义简单的GET端点
//app.MapGet("/", () => "Hangfire Running!");

app.Run();
